package com.deli.utils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * @Description: 发送文件的客户端
 * @Author: xudeli
 * @CreateDate: 2018/8/20 16:01
 **/
public class FileTransferClient extends Socket {

    private static final String SERVER_IP = "172.20.10.6";//服务端ip地址

    private static final int SERVER_PORT = 8888; //服务端端口号

    private Socket client;

    private FileInputStream fis;

    private DataOutputStream dos;

    public FileTransferClient() throws Exception {
        super(SERVER_IP, SERVER_PORT);
        this.client = this;
        System.out.println("client port :" + client.getLocalPort() + "成功连接服务端");
    }

    public void sendFile() throws Exception {
        try {
            System.out.println("====开始发送文件====");
            File file = new File("E:\\123\\Locker.bat");
            if (file.exists()) {
                fis = new FileInputStream(file);
                dos = new DataOutputStream(client.getOutputStream());
                dos.writeUTF(file.getName());
                dos.flush();
                dos.writeLong(file.length());
                dos.flush();
                System.out.println("===开始传输文件===");
                byte[] bytes = new byte[1024];
                int length = 0;
                long progress = 0;
                while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
                    dos.write(bytes, 0, bytes.length);
                    dos.flush();
                    progress += length;
                    System.out.println("[" + (100 * progress / file.length()) + "]");
                }
                System.out.println("===完成传输===");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dos != null) {
                    dos.close();
                }
                if (fis != null) {
                    fis.close();
                }
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println("FileTransferClient.start");
            FileTransferClient client = new FileTransferClient();
            client.sendFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
